(defpackage translator
  (:use :cl))
(in-package :translator)

(defvar *config-file* "~/.toolbox/translator/translator_config.json")

(defclass appinfo () ((key
		       :initarg :key
		       :accessor appinfo-key)
		      (secret
		       :initarg :secret
		       :accessor appinfo-secret)))

(defun appinfo-to-json (app)
  (com.inuoe.jzon:stringify app :stream nil :pretty t))

(defun make-appinfo (key secret)
  (make-instance 'appinfo :key key :secret secret))

(defun load-config ()
  (let* ((json-str (uiop:read-file-string *config-file*))
	(json-value (com.inuoe.jzon:parse json-str)))
    (make-appinfo (gethash "key" json-value) (gethash "secret" json-value))))

(defun read-config (str)
  (format *query-io* "translator> ~a: " str)
  (force-output *query-io*)
  (read-line *query-io*))

(defun init-config ()
  (ensure-directories-exist *config-file*)
  (if (uiop:file-exists-p *config-file*)
      (load-config)
      (let* ((key (read-config "请输入app-key"))
	    (secret (read-config "请输入app-secret"))
	    (app-info (make-appinfo key secret))
	    (json-str (appinfo-to-json app-info)))
	(progn
	  (with-open-file (out *config-file*
			       :direction :output
			       :if-exists :supersede)
	    (format out json-str))
	  app-info))))
